import {ref, onMounted, nextTick} from "vue";
import {onHide, onLoad, onPageScroll, onReachBottom, onShow, onUnload} from "@dcloudio/uni-app";
import useZPaging from "z-paging/components/z-paging/js/hooks/useZPaging";
import {
    cancelGFOrderAPI,
    cancelOrderAPI,
    getOrderGFListsAPI, oneKeyCuiShenAPI,
    queryGFOrderStateAPI,
    resumeOrderAPI,
    submitOrderAPI,
    uploadOrderIdAPI
} from "../../services/order";
import {useOrderInfoStore} from "../../stores/modules/orderInfo";
import {useUserInfoStore} from "../../stores/modules/userInfo";
import {conUtils} from "../../utils/conUtils";
import {getBindPidAPI, getUserInfoAPI} from "../../services/me";
import {useCommonInfoStore} from "../../stores/modules/commonInfo";
import {toMiniAppBusiness, toMiniAppSearch} from "../../utils/utils";

export const useOrder = () => {
    // 公共信息
    const commonInfoStore = useCommonInfoStore()
    // 用户信息
    const userInfoStore = useUserInfoStore()
    // 订单刷新信息
    const orderInfoStore = useOrderInfoStore()
    const paging = ref(null)
    useZPaging(paging)
    // 创建一个选择器查询对象，用于后续的DOM操作
    const query = uni.createSelectorQuery();
    // 数据源
    let dataList = ref([])
    // 顶部菜单
    const tabsList = ref([
        {
            name: '全部订单',
            shopActivityListParent: [],
            page: 1,
            limit: 10,
            finishLoad: false, // 加载是否没有数据数据了
            isFirst: true, // 是否第一次刷新
            triggered: false, // 刷新状态
            isNeedRefresh: false, // 是否需要刷新
        },
        {
            name: '进行中',
            shopActivityListParent: [],
            page: 1,
            limit: 10,
            finishLoad: false,
            isFirst: true,
            triggered: false,
            isNeedRefresh: false,
        },
        {
            name: '已完成',
            shopActivityListParent: [],
            page: 1,
            limit: 10,
            finishLoad: false,
            isFirst: true,
            triggered: false,
            isNeedRefresh: false,
        },
        {
            name: '已取消',
            shopActivityListParent: [],
            page: 1,
            limit: 10,
            finishLoad: false,
            isFirst: true,
            triggered: false,
            isNeedRefresh: false,
        }
    ])
    // 菜单状态
    const status = ref(-1)
    // 当前Tab的Index
    // const current = ref(0)
    // 是否显示刷新组件 弃用
    const isShowPaging = ref(true)
    // 是否保存订单状态
    const saveOrderStatus = ref(false)
    // 弹窗数据
    const modal_title = ref()
    const comment_rule = ref()
    const listID = ref()
    const order_con = ref()
    const minTime = ref()
    const modal_show = ref()
    // 是否显示进店方式
    const showSelect = ref(false)
    // 是否显示二维码进店
    const showEwm = ref(false)
    // 是否显示复制店名搜索
    const showCopy = ref(false)
    // 关闭弹出
    const isClose = ref(true)
    // 是否是H5
    const isH5 = ref(false)
    // 复制店名进店时是否不再显示进店提示
    const isNoShow = ref(commonInfoStore.isNoShow)
    // 店铺数据
    const shop = ref()
    // 活动数据
    const activity_item = ref()
    // 进店列表
    const chooseList = ref([
        {
            icon: "home", name: "小程序进店"
        },
        // #ifdef MP
        // {
        //     icon: "scan", name: "识别二维码进店"
        // },
        // #endif
        // {
        //     icon: "star", name: "复制店铺名搜索"
        // }
    ])
    const chooseList1 = ref([
        {
            icon: "home", name: "小程序进店"
        },
        // #ifdef MP
        // {
        //     icon: "scan", name: "识别二维码进店"
        // },
        // #endif
        // {
        //     icon: "star", name: "复制店铺名搜索"
        // }
    ])
    const chooseList2 = ref([
        {
            icon: "home", name: "小程序进店"
        },
        // {
        //     icon: "star", name: "复制店铺名搜索"
        // }
    ])
    // 老订单是否刷新
    const dataListOld = ref(false)
    // 倒计时秒数
    const count = ref(3)
    // 倒计时对象
    const time = ref()
    // 是否刷新
    const isRefresh = ref()
    // 是否第一次获取数据
    const isFirst = ref(true)
    // 用户信息
    const user = ref()
    // 恢复订单弹窗是否显示
    const recoveryShow = ref(false)
    // 会订单的Index
    const recoveryIndex = ref(0)
    // 关闭弹出
    const closePop = () => {
        isClose.value = false
        showCopy.value = false
    }
    // tab切换
    const currentNum = ref(0)
    const tabChange = (tab) => {
        console.log('tab切换=', tab)
        isRefresh.value = false
        currentNum.value = tab.index
        status.value = tab.index - 1
        isShowPaging.value = true
        paging?.value.reload();
    }
    // 监听跳转
    const handleLaunch = (tab) => {
        showSelect.value = false
        showCopy.value = false
    }
    // 监听错误
    const handleError = (tab) => {
    }
    // 恢复订单
    const itemResume = async () => {
        recoveryShow.value = false
        const res = await resumeOrderAPI(dataList.value[recoveryIndex.value].id)
        await uni.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
        });
        // 本地修改状态,省掉刷新再次调用接口
        dataList.value[recoveryIndex.value].is_cancel = 0
        dataList.value[recoveryIndex.value].is_resume = 0
        dataList.value[recoveryIndex.value].status = res.result.status
        dataList.value[recoveryIndex.value].check_status = res.result.check_status
        dataList.value[recoveryIndex.value].end_time = res.result.end_time
        dataList.value[recoveryIndex.value].is_cancel = res.result.is_cancel
    }
    // 恢复订单
    const handleResumeOrder = async (item, orderIndex) => {
        console.log("orderIndex", orderIndex)
        recoveryShow.value = true
        recoveryIndex.value = orderIndex
    }
    // 上传凭证
    // 获取设备信息
    let deviceInfo = uni.getSystemInfoSync().uniPlatform
    const handleUpload = async (id, source) => {
        console.log('来源==', source)
        if (deviceInfo == 'app'){
            uni.navigateTo( {
                url: "/pages_order/order_app_voucher?orderID=" + id + "&source=" + source
            })
        } else {
            uni.navigateTo( {
                url: '/pages_order/order_voucher?orderID=' + id + "&source=" + source
            })
        }
        /* await uni.navigateTo({
            url: '/pages_order/order_voucher?orderID=' + id + "&source=" + source
            // url: '/pages_order/voucher?orderID=' + id
            // url: '/pages_order/shop_process?orderId=' + id + '&isProcessTip=true&ShowScreenshot=' + ShowScreenshot.value
        }) */
    }
    // 一键催审
    const oneKeyCuiShenFun = async (item) => {
        const res = await oneKeyCuiShenAPI(item.id)
        await uni.showToast({
            title: res.msg,
            icon: 'success',
            duration: 1500,
        })
    }
    // 无需评鉴的直接提交审核
    const handleUploadOrderNo = async (id, source) => {
        const res = await submitOrderAPI({order_id: id})
        // 刷新页面
        paging?.value.reload();
        if (res.code == 200){
            await uni.showToast({
                title: res.msg,
                icon: 'none',
                duration: 1500,
            })
        }
        /* await uni.navigateTo({
            url: '/pages_order/order_voucher?orderID=' + id + "&source=" + source
            // url: '/pages_order/voucher?orderID=' + id
            // url: '/pages_order/shop_process?orderId=' + id + '&isProcessTip=true&ShowScreenshot=' + ShowScreenshot.value
        }) */
    }
    // 保存订单号
    const handleSaveUserPayOrderNo = async (item) => {
        let reg = /^[0-9]*$/
        if (!item.user_pay_order_no) {
            await uni.showToast({
                title: '请先添加外卖订单号再操作',
                icon: 'none',
            })
            return
        } else {
            if (item.user_pay_order_no.indexOf(' ') !== -1) {
                item.user_pay_order_no = item.user_pay_order_no.replace(/\s*/g, '')
            } else {
                if (!reg.test(item.user_pay_order_no)) {
                    await uni.showToast({
                        title: '输入纯数字订单号',
                        icon: 'none',
                    })
                    return
                }
                if (item.user_pay_order_no.length !== 18 && item.user_pay_order_no.length !== 19) {
                    // await uni.showToast({
                    //     title: '请输入18位或者19位订单号',
                    //     icon: 'none'
                    // })
                    // return
                }
            }
        }
        const res = await uploadOrderIdAPI(item.id, item.user_pay_order_no)
        await uni.showToast({
            title: "提示："+res.msg,
            icon: 'none',
            duration: 3000
        });
        saveOrderStatus.value = true
        item.status = res.result.status
        item.is_resume = 0
        item.check_status = res.result.check_status
        item.end_time = res.result.end_time
        item.is_cancel = res.result.is_cancel
        conUtils("new check_status", item.check_status)
        conUtils("new status", item.status)
        conUtils("new is_cancel", item.is_cancel)
        conUtils("new is_resume", item.is_resume)
        setTimeout(() => {
          paging?.value.reload();
        }, 2000)
    }
    // 再来一单
    const handleTwoOrder = async (item, activityId) => {
        conUtils("handleTwoOrder", item)
        conUtils("handleTwoOrder", activityId)
        if (item.activity.is_open === 0) {
            await uni.showToast({
                title: '活动已结束',
                icon: 'none'
            })
            return
        }
        await uni.navigateTo({
            url: '/pages_shopdetail/shopdetail?id=' + item.shop.id + '&activityId=' + activityId
        })
    }
    // 查看审核不过的原因
    const reasonForrejection = async (item) => {
        modal_title.value = '驳回不可提交原因'
        comment_rule.value = item.shop_activity_ask
        listID.value = item.id
        order_con.value = item.check_refuse_reason
        minTime.value = 0
        modal_show.value = true
    }
    // 获取用户信息
    const getUserInfo = async () => {
        const res = await getUserInfoAPI()
        user.value = res.result
        userInfoStore.setUserInfo(user.value)
        // 设置分销商
        // if (commonInfoStore.resellerId && !user.value.reseller_id) {
        //   await getBindResellerIdAPI(commonInfoStore.resellerId)
        // }
        // 设置推荐人
        if (commonInfoStore.parentId && !user.value.parent_id) {
            await getBindPidAPI(commonInfoStore.parentId)
        }
    }
    // 取消订单
    const cancelOrder = async (item) => {
        uni.showModal({
            title: '提示',
            content: '您是否确认取消订单?',
            success: async function (res) {
                if (res.confirm) {
                    const res = await cancelOrderAPI(item.id)
                    await uni.showToast({
                        title: res.msg,
                        icon: 'none',
                        duration: 2000
                    });
                    // 本地修改状态,省掉刷新再次调用接口
                    item.is_cancel = 1
                    item.is_resume = 1
                    item.status = res.result.status
                    item.check_status = res.result.check_status
                    item.end_time = res.result.end_time
                    item.is_cancel = res.result.is_cancel
                    // setTimeout(() => {
                    //   paging?.value.reload();
                    // }, 1000)
                }
            }
        });
    }
    // 获取订单数据
    const queryList = (pageNo, pageSize) => {
        if (!userInfoStore.isLoginBool()) {
            orderInfoStore.isRefresh = true
            paging?.value.complete(false);
            return
        }
        getOrderGFListsAPI({
            status: status.value + '',
            limit: pageSize,
            page: pageNo
        }).then(res => {
            dataListOld.value = true
            res.result.forEach(item => {
                item.now_time = new Date().toISOString().slice(0, 10)
            })
            console.log('订单数据=',  res.result)
            if (isShowPaging.value) {
                setTimeout(() => {
                    paging.value?.complete(res.result);
                }, 600)
                isShowPaging.value = false
            } else {
                paging.value?.complete(res.result);
            }
        }).catch(() => {
            paging.value?.complete(false);
        })
    }
    // 监听页面滚动
    const onPageScroll = (e) => {
        closeMore() // 页面滚动关闭更多
    }
    // 去店铺
    const goShop = async (item) => {
        conUtils(item)
        chooseList.value = chooseList1.value
        shop.value = item.shop
        activity_item.value = item
        // 获取type类型
        /* chooseList.value.forEach((itemC, index) => {
            // 直接进入店铺下单
            onChooseList(chooseList.value.length>2?index:index===1?2:index)
        }) */
        // 进店方式弹窗
        showSelect.value = true
    }
    // 去美团搜索
    const goMeiTuanSearch = async () => {
        showCopy.value = false
        await toMiniAppSearch(shop.value.order_type == 2 || shop.value.order_type == 3 ? 1 : shop.value.type)
    }
    // 选择进店方式
    const onChooseList = (type) => {
        showSelect.value = false
        clearTime()
        switch (type) {
            case 0:
                if (shop.value.order_type == 2 || shop.value.order_type == 3) {
                    toMiniAppBusiness(1, shop.value.wxPath)
                    return
                }
                toMiniAppBusiness(shop.value.type, shop.value.path)
                break;
            case 1:
                showEwm.value = true
                break;
            case 2:
                uni.setClipboardData({
                    data: shop.value.order_type == 2 || shop.value.order_type == 3 ? shop.value.shop_name : shop.value.name,
                    success() {
                        uni.hideToast();
                    }
                })
                if (isNoShow.value === false) {
                    showCopy.value = true
                    djsToMeiTuan(2) //倒计时类型搜索
                } else {
                    goMeiTuanSearch()
                }
                break;
        }
    }
    const clearTime = () => {
        if (time.value) {
            clearInterval(time.value)
            count.value = 3
        }
    }
    // 跳转美团
    const djsToMeiTuan = async (type) => {
        // #ifdef H5
        if (isH5) {
            return
        }
        // #endif
        if (time.value) {
            clearInterval(time.value)
            count.value = 3
        }
        time.value = setInterval(async () => {
            count.value = count.value - 1
            conUtils(" count.value", count.value)
            if (count.value <= 0) {
                conUtils(" count.value--type", type)
                clearInterval(time.value)
                if (type === 0 && isClose.value) {
                    conUtils("djsToMeiTuan", type)
                    // await doMeiTuanAndQiangDan()
                } else if (type === 1 && isClose.value) {
                    conUtils("djsToMeiTuan", type)
                    await goShop()
                } else if (isClose.value) {
                    conUtils("djsToMeiTuan", type)
                    await goMeiTuanSearch()
                }
                isClose.value = true
                count.value = 1
            }
        }, 1000)
    }
    // 点击不在显示
    const onClickIsNoShow = () => {
        isNoShow.value = !isNoShow.value
        conUtils("isNoShow.value", isNoShow.value)
        commonInfoStore.setIsNoShow(isNoShow.value)
    }
    // 取消官返订单
    const cancelGFOrder = async (item) => {
        console.log(item, ',item.channel_id')
        await cancelGFOrderAPI(item.userEventId)
        item.code = 2
    }
    // 跳转官返店铺
    const goGFShop = (item) => {
        conUtils("goGFShop", item)
        // uni.navigateToMiniProgram({
        //   appId: item.wxAppid,
        //   path: item.wxPath,
        // })
        chooseList.value = chooseList2.value
        shop.value = item
        activity_item.value = item
        /* chooseList.value.forEach((itemC, index) => {
            // 直接进入店铺下单
            onChooseList(chooseList.value.length>2?index:index===1?2:index)
        }) */
        // 进店方式弹窗
        showSelect.value = true
    }
    // 查询官返订单状态
    const queryGfState = async (item) => {
        const res = await queryGFOrderStateAPI(item.userEventId)
        console.log('官返返回的状态值=',res)
        conUtils("queryGfState", res)
        modal_title.value = '当前官返订单状态'
        comment_rule.value = item.shop_name
        listID.value = item.id
        order_con.value = res.result.msg
        minTime.value = 0
        modal_show.value = true
        item.code = res.result.code
    }

    // 刷新时间监听
    const onRefresh = async () => {
        isRefresh.value = true
    }
    // 隐藏更多按钮事件setMore
    const activeMorenIndex = ref(-1)
    const closeMore = (e) => {
        conUtils('e',e)
        activeMorenIndex.value = -1
    }
    // 点击更多按钮事件
     const setMore = (item) => {
         activeMorenIndex.value = item
     }
    onPageScroll(e => {
    })
    onReachBottom(() => {
    })
    onShow(() => {
        isRefresh.value = false
        // 是否刷新订单列表
        if (orderInfoStore.isRefresh && dataListOld.value && !isFirst) {
            conUtils("onShow", "1111111111111111111")
            orderInfoStore.setIsRefresh(false)
            paging?.value?.reload();
        } else if (dataListOld.value) {
            conUtils("onShow", "22222222222222222222222222")
            isRefresh.value = true
            paging?.value?.refresh();
        } else {
            paging?.value?.reload();
        }
        if (userInfoStore.isLoginBool() && !user.value && !userInfoStore.userInfo && !isFirst) {
            getUserInfo()
        }
        isFirst.value = false
        // 判断是否登录
        userInfoStore.isLogin()
    })
    onLoad(async (options) => {
        // #ifdef H5
        commonInfoStore.initJSDKConfig()
        isH5.value = true
        // #endif
        let listItem = tabsList.value[0]
        if (listItem.isFirst) {
            listItem.isFirst = false
            listItem.triggered = true
        }
        // tab页面加载时默认选中的索引
        currentNum.value = options.current
        if (options.current){
            status.value = Number(options.current) - 1
        } else {
            status.value = -1
        }
        console.log('status=', status.value)
    })

    onUnload(() => {
        clearTime()
    })
    onHide(() => {
        clearTime()
    })
    onShow(() => {
        clearTime()
    })

    return {
        commonInfoStore,
        userInfoStore,
        orderInfoStore,
        paging,
        dataList,
        tabsList,
        status,
        // current,
        isShowPaging,
        saveOrderStatus,
        modal_title,
        comment_rule,
        listID,
        order_con,
        minTime,
        modal_show,
        showSelect,
        showEwm,
        showCopy,
        isClose,
        isH5,
        isNoShow,
        shop,
        activity_item,
        chooseList,
        chooseList1,
        chooseList2,
        dataListOld,
        count,
        time,
        isRefresh,
        user,
        recoveryShow,
        recoveryIndex,
        currentNum, // tab 切换时，当前tab索引
        activeMorenIndex, // 关闭更多按钮索引
        closePop,
        tabChange,
        handleLaunch,
        handleError,
        itemResume,
        handleResumeOrder,
        handleUpload,
        oneKeyCuiShenFun, // 一键催审
        handleUploadOrderNo,
        handleSaveUserPayOrderNo,
        handleTwoOrder,
        reasonForrejection,
        getUserInfo,
        cancelOrder,
        queryList,// 获取订单列表
        onPageScroll, // 监听页面滚动
        goShop,
        goMeiTuanSearch,
        onChooseList,
        clearTime,
        djsToMeiTuan,
        onClickIsNoShow,
        cancelGFOrder,
        goGFShop,
        queryGfState,
        onRefresh,
        closeMore, // 隐藏更多按钮
        setMore, //点击更多按钮
    }
}